import tkinter as tk
from tkinter import filedialog, messagebox
import os
import pandas as pd
import requests,os

def excel_to_dict(file_path):
    # Read the Excel file
    df = pd.read_excel(file_path, engine="openpyxl", header=0)

    # Ensure there are at least three columns
    if df.shape[1] < 3:
        raise ValueError("Excel file must have at least three columns.")

    # Extract the second and third column
    column_1 = df.iloc[:, 0]  # Second column (Values)
    column_3 = df.iloc[:, 2]  # Third column (Keys)

    # Convert to dictionary
    result_dict = dict(zip(column_3, column_1))

    return result_dict


def download_image(image_url, save_name):
    try:
        # Send HTTP GET request to the image URL
        response = requests.get(image_url, stream=True)
        
        # Check if the request was successful
        if response.status_code == 200:
            with open(save_name, 'wb') as file:
                file.write(response.content)
            print(f"✅SUCCESS: {save_name}")
        else:
            print(f"❌FAIL: {response.status_code}")
    
    except Exception as e:
        print(f"⚠️ Error: {e}")

def select_file():
    """选择 PNG 文件并显示路径"""
    file_path = filedialog.askopenfilename()
    if file_path:
        entry_path.delete(0, tk.END)
        entry_path.insert(0, file_path)

def images_download():
    excel_path = entry_path.get()

    if not os.path.exists(excel_path):
        messagebox.showerror("错误", "请选择有效的EXCEL文件")
        return

    try:
        data_dict = excel_to_dict(excel_path)
        folder_path=os.path.dirname(excel_path)+'/原图下载'

        for key, value in data_dict.items():
            image_url = value
            if not os.path.exists(folder_path):
                os.makedirs(folder_path)
            pic_path=os.path.join(folder_path,key+'.jpg')
            download_image(image_url,pic_path)

    except Exception as e:
        messagebox.showerror("错误", f"转换失败: {str(e)}")

# 创建 GUI 窗口
root = tk.Tk()
root.title("PNG 转 JPG [size<2M]")

# 设置窗口大小
root.geometry("400x150")

# 标签
label = tk.Label(root, text="文件夹：")
label.pack(pady=5)

# 输入框
entry_path = tk.Entry(root, width=40)
entry_path.pack(pady=5)

# 选择按钮
btn_select = tk.Button(root, text="选择", command=select_file)
btn_select.pack(pady=5)

# 执行按钮
btn_execute = tk.Button(root, text="执行", command=images_download)
btn_execute.pack(pady=5)

# 运行 Tkinter 主循环
root.mainloop()
